/*
 * UI3.0导入功能，导入主表和子表
 */
define(["jquery","ecp.utils","ecp.service","ecp.component.dialog","ecp.component.ImportResult","ecp.utils.i18n","ecp.component.ajaxfileupload"],function($,utils,ecp,$window,importResult,i18n){
	var SVC_PKG = "com.ygsoft.ecp.app.operator.system.service.context",
		IMPORT_CTX = SVC_PKG+".IDocumentImportContext",
		ATTACH_CTX = "com.ygsoft.ecp.service.unstructure.service.context.IEntityAttachmentContext",
		//行处理器
		ROW_HANDLER = "com.ygsoft.ecp.app.operator.system.impl.context.serverimport.DefaultGldxImportRowHandler",
		PATH = utils.getRootPath()+"ecp/webcore/components/import/",
		NS = "com.ygsoft.ecp.operator.system",
		RESULT_JS =PATH+"js/"+NS+".ImportResult.js";
//		Log = $.ecp.getLog(NS+".Import");
	var EcpImport = function(control){
		this.control = control;
	}
	
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	EcpImport.prototype = {
			
		/**
		 * 是否有校验结果信息.
		 * @param {Object[]} r 结果
		 */
		isResultEmpty : function(r) {
			if (!r || r.length == 0){return true;}
			for (var i = 0; i < r.length; i++) {
				if (r[i].code === 0){ continue;}
				
				var sheets = r[i].sheetResults;
				if (!sheets){ continue;}
				
				for (var key in sheets) {
					var sheet = sheets[key],
					    rows = sheet.rowResults;
					if (rows && rows.length > 0){ return false;}
				}
			}
			
			return true;
		},
		
		/**
		 * 多文件上传.
		 */
		multiImport : function(option) {
			option = option || {};
			var uploadOption = {
				maxnumber : 3,
				maxsize : 10,
				filterExt : "et_xls_xlsx"
			};
			$.extend(uploadOption, option);

			var me = this;
			
			var upload = new ecp.ui.datafield.UpLoador(uploadOption);
			upload.onCallBack(function(ywKey, fileNames) {
				var scheme = option.scheme || {};
				 
				var result = ecp.RemoteService.doPost(IMPORT_CTX,"doImport",[DataContextUtil.getEcpDataContext(),ywKey, scheme]);
				if (option.autoShow && !me.isResultEmpty(result)) {
					$.ecp.jsImport(RESULT_JS);
					//异常显示列表
					$.ecp.Document.showImportResult(result);
				}
				if (option.callback) {
					try {
						option.callback.call(null, result);
					} catch (e) {
						Log.warn("执行函数失败：" + option.callback + " 原因：" + e.message);
					}
				}
		 	});
		},
		/**
		 * 绑定事件
		 */
		initEvent : function(vOpt) {
			var me = this,
				container = me.winContainer,
				browBtn = $("#browBtn", container),
				importFile = $("#importFile", container),
				importFilePath = $("#importFilePath", container);
			importFile.change(function() {
				if (me.validateFile(vOpt)) {
					var fileName = importFile.val();
					importFilePath.val(fileName.substring(fileName.lastIndexOf("\\")+1));
				} else {
					importFilePath.val("");
					importFile.val("");
				}
			});
		
			browBtn.click(function() {
				importFile.click();
			});
			if(this.loadMode){
				this.loadMode.onClick(function(){
					var sel = arguments[2];
					var dataModeUI = $.ecp.getUI("#dataMode");
					if(dataModeUI){
						dataModeUI.value("add");
						if(sel=="todb"){
							dataModeUI.enable("update");
							dataModeUI.disable("override");
						}else if(sel=="toui"){
							dataModeUI.enable("override");
							dataModeUI.disable("update");
						}
					}
				});
			}
			//绑定上传按钮事件
			$(".input-group-addon", container).bind("click", function(){
				importFile.trigger("click");
			})
		},
		
		/**
		 * 校验上传文件
		 */
		validateFile : function(opt) {
			var container = this.winContainer,
				importFile = $("#importFile", container),
				filePath = importFile.val().toLowerCase(),
				importMaxSize = opt.maxSize,
				importExtName = opt.extName,
				isValidExtName = false,
				extNames = importExtName.split(",");
			if(filePath.length>200){
				utils.notify(i18n.import.fileNameLength);
				return false;
			}
			for (var i = 0; i < extNames.length; i++) {
				if (filePath.indexOf(extNames[i].toLowerCase())>=0) {
					isValidExtName = true;
					break;
				}
			}
			if (!isValidExtName) {
				utils.notify(i18n.import.fileFormat);
				return false;
			}
			return true;
		},
		
		/**
		 * 开始上传文件
		 */
		save : function(modal) {
			var me = this,
				container = me.winContainer,
				importFile = $("#importFile", container),
//				dataModeUI = $.ecp.getUI("#dataMode", container),
//				loadModeUI = $.ecp.getUI("#loadMode", container),
				filePath = importFile.val(),
				importFilePath = $("#importFilePath", container).val(),
				cfqsCheck = $("#cfqs", container),
				dlgOpt = { 'auto_close': 2000 };
			if(cfqsCheck.length !== 0){
				var checked = cfqsCheck.attr("checked");
				if(checked == "checked"){
					me.cfqs = true;
				}else{
					me.cfqs= false;
				}
			}
			if (!filePath || filePath == '' || !importFilePath || importFilePath == '') {
				utils.notify(i18n.import.selectFile);
				return;
			}
			//如果有方案下拉控件，则判断必须选择一个方案才能导入
			if(me.schemeCombo && utils.isEmpty(me.schemeCombo.value())) {
				utils.notify(i18n.import.selectScheme);
				return;
			}
			//增加进度条
			var fileName, fileSize;
			if (utils.isIE()) {
				try{
					var fso = new ActiveXObject("Scripting.FileSystemObject");
					fileName = fso.GetFile(filePath).name;
					fileSize = fso.GetFile(filePath).size;
				}catch(e){
					fileName = $(importFile).val();
					fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
					fileSize = 8192;
				}
			} else {
				fileName = importFile[0].files[0].name;
				fileSize = importFile[0].files[0].size;
			}
			
//			me.dataMode = dataModeUI && dataModeUI.getValue();
//			me.loadMode = loadModeUI && loadModeUI.getValue();
			//默认为追加模式
//			if(!me.dataMode){
//				me.dataMode = "add";
//			}
//			if(!me.loadMode){
//				me.loadMode = "toui";
//			}
			
			me.ywKey = Math.uuid();
			me.resId = Math.uuid();
			
			$.ajaxFileUpload({
				url : utils.getEcpUrl("FileAccessServlet"),
				secureuri : false,
				fileElementId : 'importFile',
				businessParams : {
					"beanId" : SVC_PKG+".IUnstructureTransferContext",
					"method" : "saveFile",
					"operParams" : {
						"p1" : {
							"title" : fileName,
							"bsize" : fileSize,
							"resId" : me.resId,
							"ywkey" : me.ywKey,
							"remark" : "",
							"modelState" : 4,
							"attachmentDetailVO" : {}
						}
					}
				},
				dataType : 'text',
				success : function(data, status) {
					var opt = me.winOpt = {};
					opt.ywKey = me.ywKey;
					opt.resId = me.resId;
					opt.dataMode = me.dataMode;
					opt.loadMode = me.loadMode;
					opt.cfqs = me.cfqs;
					modal.modal('hide');
				},
				error : function(data, status, e) {
					utils.notify(data);
				}
			});
		},
		/**
		 * 上传文件
		 */
		doImport : function(opt) {
			var vOpt = {
				maxSize : 10,
				extName : "et,xls,xlsx"
			};
			$.extend(vOpt, {
				maxSize : opt.maxSize || vOpt.maxSize,
				extName : opt.extName || vOpt.extName
			});
		
			var me = this,
				cid = opt.classId,
				tid = opt.typeId,
				scenceId = opt.scenceId;
			me.option = opt;
			//获取是否导入后取数
			var uOpt = {
//				templateUrl : opt.url,
//				isSave : opt.isSave,
//				useSchemeSet : opt.useSchemeSet,
				importMaxSize : vOpt.maxSize,
				importExtName : vOpt.extName,
//				entity_import : opt.entityImport,
			    scheme_classId : cid,
			    scheme_typeId : tid,
			    scheme_scenceId: scenceId,
//				targetColModel:  opt.targetColModel,
//				targetColNames: opt.targetColNames,
//			    scheme_datafield : opt.datafield,
			    formatId : opt.formatId,
				showCloseButton:false,
				otherButtons:[i18n.import.cancel,i18n.import.exportBtn],
                otherButtonStyles:['btn-default', 'btn-primary'],
                clickButton : function(sender, modal, index){
                    if(index == 0){ 
                        modal.modal('hide');
                    }
                    if(index == 1){
                        //"导入"按钮
                        me.save(modal);
                    }
                },
                callback:function(container){
                	me.winContainer = container.parent();
                	utils.loadLocale(i18n.import,me.winContainer);
    				utils.domAttrI18n(i18n.import, me.winContainer, "title");
    				utils.domAttrI18n(i18n.import, me.winContainer, "placeholder");
                	me.initEvent(vOpt);
                },
				dialogHide : function(_win) {
					
					var wOpt =  me.winOpt;
					if(!wOpt){return;}
					var	ywKey = wOpt.ywKey,
						resId = wOpt.resId,
						loadMode = wOpt.loadMode,
						dataMode = wOpt.dataMode;
					me.cfqs = wOpt.cfqs;
					if (ywKey && resId) {
//						wOpt.ywKey = null;
//						wOpt.resId = null;
						//modify by yinshanpeng on 2014.9.25
						var scheme = opt.scheme || {upLoadOnly : true};
						scheme.tokenId = $.cookie("ecpDataContext.tokenId");//$.ecp.baseConfig.getEcpToken();
						scheme.classId = cid;
						scheme.typeId = tid;
						scheme.scenceId = scenceId;
						if(wOpt.isSave){
							scheme.dataMode = "gldxImport";
						}
						//非直接入库
						//调用服务程序，校验数据，返回正确的（validData)和错误的记录(invalidData)
						/*
						 * result.sheetResults={0(sheet): {},1(sheet):{validData:{1(行):{valueMap:{DW: "400065274",...} }},invalidData:{}}}
						 *  
						 *  如果是简单导入，result中还应包含scheme,否则界面填值时，无法进行。
						 *  by yangwenyi. 2014-12-5
						 */
						var result = ecp.RemoteService.doPost(IMPORT_CTX,"doImport",[ecp.DataContextUtil.getEcpDataContext(),ywKey, scheme]);

						//显示异常信息
						if (opt.autoShow && !me.isResultEmpty(result)) {
							importResult.showImportResult(result,{"hideBtn":opt.isSave});
						}
						var res = me.callback(result, scheme.schemeId, loadMode, dataMode, opt.callback);
//						if (opt.callback) {
//							try {
//								//这里将服务器返回的结果初始化到界面： billImport.initValue
//								opt.callback.call(me, result, me.cfqs, scheme.schemeId, loadMode, dataMode);
//							} catch (e) {
//								utils.notify(i18n.import.dataError);
//							}
//						}
						// 删除已上传的文件
						ecp.RemoteService.doPost(ATTACH_CTX,"deleteSummaryAndDetailByResId", [resId]);
//						$.unblockUI();
					}
				}
			};
			
			var importWinUrl = PATH + "simpleImportWin.html";
			if (opt.useSchemeSet) {
				//方案导入
//				uOpt.title = EcpTool.getLg("importScheme.importByScheme","根据方案导入");
//				importWinUrl = PATH + "importWithSchemeSet.html";
			}else{
				uOpt.title = i18n.import.importData;
				uOpt.url = importWinUrl;
				uOpt.width = "500px";
			}
			var win  = $window.window(uOpt);
			win.find(".modal-footer").children().first().before('<div class="winControlBox" style="text-align:right;float: left;"> <label class="checkbox-inline"><input type="checkbox" id="cfqs" name="checkbox11" value="1" checked="">&nbsp;&nbsp;&nbsp;&nbsp;'+i18n.import.doGetData+'</label></div>');
		},

		/**
		 * 获取Excel表格数据
		 * @param {Function} callback 回调函数
		 * @param {Object} vOpt 校验行为对象
		 */
		getExcelData : function(callback, vOpt,scheme) {
			var uOpt = { //上传选项
				width : 400,
				height : 250,
				title : "上传文件",
				modal : true,
				resizable : false,
				collapsible : false,
				minimizable : false,
				maximizable : false,
				onClose : function(_win) {
					var opt= _win.getOption(),
						ywKey = opt.ywKey,
						resId = opt.resId,
						epFP = opt.uploadFilePath,
						epFN = opt.exampleFileName;
					if (ywKey && resId) {
						opt.ywKey = null;
						opt.resId = null;
						
						var wb, 
							succ = true; //上传成功标志
						try {
							if(scheme){
								wb = $.ecp.rs.ajax4Bean(IMPORT_CTX+".getExcelData",[ywKey,scheme],false);
							}else{
								wb = $.ecp.rs.ajax4Bean(IMPORT_CTX+".getExcelData",[ywKey],false);
							}
						} catch(_e) {
							succ = false;
							Log.error(IMPORT_CTX+".getExcelData("+ywKey+")失败。"+_e.message);
							$.ecp.notify(i18n.import.uploadError);
						}
						if(!succ) {
							return false;
						}
				
						if (callback) { 
//								try {
								callback.call(null, wb, epFP, epFN);
//								} catch (e) {
//									$.ecp.notify("执行函数失败：" + callback + " 原因：" + e.message);
//									Log.warn("执行函数失败：" + callback + " 原因：" + e.message);
//								}
						}
						// 删除已上传的文件
						$.ecp.rs.ajax4Bean(ATTACH_CTX+".deleteSummaryAndDetailByResId", [resId],false);
					}
				}
			};
			$.extend(uOpt, vOpt);
			var win  = $window.window(uOpt);
		},
		
		/**
		 * 通用导入方法。
		 * opt 导入参数。
		 * 
		 * {
		 * 	useSchemeSet: false,//是否根据方案导入。
		 *  dataField:".",对应导入表格的datafield
		 *  classId : "" ,需配置方案是才需要
		 *  container: "",容器
		 *  typeId:"",需配置方案时才需要。
		 * 	schemes: [//此处可以同时处理多个页签。自定义方案导入时才需要，在 useschemeSet为false才生效
		 * 		{
		 * 			dataField:".",  //对应页面表格模型。
		 * 			startDataIndex : 2,// 数据起始行
		 * 			startColIndex:{}, //页面表格项目名称对应的导入表格起始列序。
		 * 			container : container  //容器，用于获取当前容器的元素
		 * 			items:[{columnIndex : i,propertyName : v.columnName}]  //对应的列关系及列属性，用于组装方案。
		 * 		}],
		 * 	callback : function(flag,result,scheme){回调函数用来处理数据。
		 * 		
		 * 	},
		 * 	validate : true ,是否需要经过平台校验。默认为true	
		 * 
		 * }
		 * 
		 * 
		 */
		importFile :function(opt){
			var me = this; 
			me.opt = opt;
			opt.callback && ( me.initValue = opt.callback);
			if(opt.validate !=false){//将用户自定义的callback缓存。
				opt.callback = me.callback;
			}
			me.doImport(opt);
		},
		
		/**
		 * 处理数据。
		 */
		callback : function(result, schemeId,loadMode, dataMode, callback){ 
	    	var _result0 = result[0],
	    		me = this;
	 		if( _result0.code === -3) {
	    		  utils.notify("导入失败，数据存在异常。",{},_result0.msg);
	    		  return;
            }
	    	var sheets = _result0.sheetResults;
	    	if(typeof sheets === "undefined") {
	    		utils.notify("导入数据为null");
		   		return;
		   	}
		   	//如果存在校验失败信息，则提示
		   	var validFlag = false;
			var finalResult = me._parseImportResult(sheets);
			for(var k= 0;k<finalResult.length;k++){
				if(finalResult[k].showValidInfo) {
					validFlag = true;
					break;
				}
		   	}
			function doCallback(){
				if($.isFunction(callback)){
					callback.call(me, result, me.cfqs);
				}
			}
			//数据校验失败，并存在方案是给出提醒。
			if(validFlag) {
				importResult.showImportResult(result,null,doCallback);
//				$.ecp.Document.showImportResult(result,{title : "以下记录导入失败,请修正后再导入！",callback:this.initValue,_this:me,scheme:me.schemes});
			}else{
				//这里将服务器返回的结果初始化到界面： billImport.initValue
				doCallback();
			}
	      },
	      /**
	       * 初始化数据
	       */
	      initValue : function(flag ,sheets,scheme){
	    	 if(flag===false){
	    		 utils.notify("导入数据失败。");
	    		 return;
	    	 }
	    	 var me = this, 
	    	 	 opt = this.option,
	    	 	 container = opt.container,
	    	 	 dataField = opt.dataField;
	    	 if(!container){
	    		 utils.notify("未传入被导入表格的所在容器container，有可能找不到对应的表格。");
	    	 }
	    	 if(!dataField){
	    		 utils.notify("请传入被导入表格的dataField");
	    		 return;
	    	 }
	    	 
	    	 var ecpGrid = $.ecp.getUI("[dataField='"+dataField+"']",container),
//	    	 var ecpGrid = $.ecp.getUI("[dataField='"+dataField+"']",container),
	    	 	 dataModel = ecpGrid.getDS().getDM(),
	    	 	 metaModel = ecpGrid.getDS().getMDM(),
	   	 		 items = scheme.schemeItemVOs,
	   	 		 finalResult = me.finalResult,
	   	 		 effectItem = [];
	    	 
	   	 	 if($.isArray(items)) {
	   	 		 items.each(function(item, i) {
		   			if(item.columMapVOs && item.columMapVOs.length) {
		   				effectItem.push(item);
		   			}
	   	 		});
	   	 	 }
	    	 effectItem.each(function(item, i) {
		   		var sheetI = item.sheetIndex;
		   		if(sheets[sheetI]) {
		   			var sheet = sheets[sheetI];
		   			var dataStartIndex = sheet.startDataRow; //item.dataStartIndex;
		   			var dataEndIndex =  sheet.endDataRow; //item.dataEndIndex;
		   			var dataField = item.dataField;
		   			var colMaps = item.columMapVOs;
		   			var primaryCol = item.primaryCol;
		   			var rowData = finalResult[sheetI].records;
		   			if(utils.notEmpty(rowData)) {
		   				//如果是 主表
		   				if(dataField == '.') {
		   					var $table = $("table[datafield='.']", container);
		   					var isTable = $table.length;
		   					var tableList = [];
		   					//modify by yinshanpeng on 2014.7.9
		   					var ecpTable = $.ecp.getUI($table);
		   					var primaryKey = ecpTable ? ecpTable.getPKeyName() : "ywid";
	   						for(dataStartIndex; dataStartIndex <=dataEndIndex; dataStartIndex++) {
		   						var record = rowData[dataStartIndex];
		   						if(record) {
		   							var vm =record.valueMap;
		   							if(isTable) {
		   								for(y in vm) {
		   									if(!isNaN(y * 1)) {
		   										delete vm[y];
		   									//modify by yinshanpeng on 2014.7.9
		   									} else if(y.has('.')) {
		   										var arr = y.split('.');
		   										if(typeof vm[arr[0]] === 'undefined') {
		   											vm[arr[0]] = {};
		   										}
		   										vm[arr[0]][arr[1]] = vm[y];
		   										delete vm[y];
		   									}
		   								}
		   								if($.isPlainObject(vm.xtywbillVO)) {
		   									vm.xtywbillVO.jcls = "com.ygsoft.ecp.app.ywdj.service.model.XtywbillVO";
		   								}
			   			   				vm[primaryKey] = - Math.uuid(8, 10);
			   							vm.modelState = $.ecp.constants.ModelState.NEW;
			   							vm.jcls = metaModel.get('.').getClassName();
			   							vm.classId  = metaModel.getClassId();
			   							vm.typeId  = metaModel.getTypeId();
		   								tableList.push(vm);
		   							} else {
		   								window.breakpoint();
				    					colMaps.each(function(cm, i)  {
				    						//根据df判断页面控件是否只读， 否 才赋值
				    						var control = $.ecp.getUI("[dataField='"+cm.propertyName+"']").getControl()[0];
				    						
				    						if(control && !control.readOnly) {
				    							dataModel.get(cm.propertyName).value(vm[cm.propertyName]);
				    						}

				    					});
		   							}
		   						}
		    				}
		   					
		   					if(isTable) {
		   						var ecpTable = $.ecp.getUI($table);
		   						if($.isFunction(this.transactData)){
			   						tableList = this.transactData(tableList);//如果开发人员在控制类中实现该方法，则调用该方法。
			   						if(tableList == false){//如果返回false则中断
			   							return ;
			   						}
		   						}
		   						if(scheme.importType == $.ecp.entityImport.ImportType.NEW || utils.isEmpty(primaryCol)) {
			   						ecpTable && ecpTable.changeServerPageState(true);//导入时，将表格变更为客户端分页
			   						var records = ecpTable.getControl()[0].p.records;
			   						ecpTable.value(tableList);
			   						ecpTable._initAmountRows();//根据页面信息设置合计行 modify fuxiaopan
	//		   						处理导入之后页码显示问题。目前是显示总记录数，但是分页处理只处理导入之后的数据
		  							records = ecpTable.getControl()[0].p.records = tableList.length + records;
			   						ecpTable.getControl()[0].updatepager(true,true,"导入&nbsp;"+tableList.length+"&nbsp;条，");
			   						ecpTable.bind("beforeClickPage",function(page){
			   							ecpTable.getControl()[0].p.records = records;
			   							ecpTable.getControl()[0].updatepager(true,true,"导入&nbsp;"+tableList.length+"&nbsp;条，");
			   						});
			   					}else if(scheme.importType == $.ecp.entityImport.ImportType.MODIFY) {
		   							//获取表格所有数据
		   							var gridParam =ecpTable.getGridParam(),
	  								pageCnt = gridParam.lastpage;
	  								ecpTable.getRangeData({begin:1,end:pageCnt},function(gridDatas){ // 表格取数（走客户端）
										 //导入时，将子表格变更为客户端分页
				   						ecpTable.changeServerPageState(true);
			   							var newData = me.matchDataForModify(gridDatas, tableList, primaryCol,primaryKey);
			   							ecpTable.value(newData);
			   							
									});  
		   						}
			   					
		   					}
		   		     // 子表
		   				} else {
		   					var jcls = null;
		   					var billClassId = null;
							var billTypeId = null;
		   					var refValues = metaModel.get(dataField).getRefTypeValues();
		   					if(refValues && refValues.length) {
		   						billClassId = refValues[0].classId;
		   						billTypeId = refValues[0].typeId;
		   						//jcls = that.IMetaModelContext.getClassName(billClassId,billTypeId);
		   						jcls = $.ecp.rs.synGetService(META_CTX+".getClassName",[billClassId,billTypeId]);
		   					}
		   					var subGridData = [];
		   					for(dataStartIndex; dataStartIndex <=dataEndIndex; dataStartIndex++) {
		   						var record = rowData[dataStartIndex];
		   						if(record) {
		   							var vm =record.valueMap;
		   							for(z in vm) {
										if(!isNaN(z * 1)) {
											delete vm[z];
										}
									}
		   							vm['gid'] = - Math.uuid(8, 10);
		   							vm.modelState = $.ecp.constants.ModelState.NEW;
		   							vm.jcls = jcls;
		   							vm.classId  =billClassId;
		   							vm.typeId  = billTypeId;
		   	   						subGridData.push(vm);
		   						}
			    			}
		   					
		   					var subGrid = $.ecp.getUI("[datafield='"+dataField+"']", container);
		   					//由于单据动态变更dataField。如果是这种情况无法获取子表，通过下面方式获取。
		   					if(!subGrid){
		   						var subGrid = $.ecp.getUI("[datafield $='"+dataField+"']", container);
		   					}
		   					if(subGrid) {
		   						
		   						if(scheme.importType == $.ecp.entityImport.ImportType.NEW || utils.isEmpty(primaryCol)) {
			   						//导入时，将子表格变更为客户端分页
			   						subGrid.changeServerPageState(true);
		   							subGrid.value(subGridData);
			   						
			   						//根据页面信息设置合计行 modify fuxiaopan
				   					subGrid._initAmountRows();
		   						} else if(scheme.importType == $.ecp.entityImport.ImportType.MODIFY) {
		   							//获取表格所有数据
		   							var gridParam =subGrid.getGridParam(),
	  								pageCnt = gridParam.lastpage;
		   							subGrid.getRangeData({begin:1,end:pageCnt},function(gridDatas){ // 表格取数（走客户端）
										 //导入时，将子表格变更为客户端分页
				   						subGrid.changeServerPageState(true);
			   							var newData = me.matchDataForModify(gridDatas, subGridData, primaryCol,subGrid.getName());
			   							subGrid.value(newData);
			   							
									});  
			   						
		   						}
		   					}
		   				}
			   		}
			   	}
			 });
		   	//触发项目运算
			if(dataModel.get(".").hasChange()){
				 try{
					 $.ecp.exp.exp_eval(metaModel, null, dataModel, null, null, null, false);
				 }catch(e){
					 $.ecp.notify("导入后触发项目运算失败。");
				 }
		    }
			me.option = null;
			me.finalResult = null;
	      },
	      
	      /**
	       * 查询 指定方案ID的方案
	       * 
	       * @schemeId : 方案ID
	       */
		 querySchemeBySchemeId : function(schemeId){
			//return this.IImportSchemeContext.findByExample({schemeId:schemeId,jcls:"com.ygsoft.ecp.app.operator.system.service.model.ImportSchemeVO"},1,1);
			return $.ecp.rs.synPostService("com.ygsoft.ecp.app.operator.system.service.context.IImportSchemeContext.findByExample",[{schemeId:schemeId,jcls:"com.ygsoft.ecp.app.operator.system.service.model.ImportSchemeVO"},1,1]);
		 },
		 
		/**
		 * 对比表格已有数据和将要导入的数据，修改已存在的记录，新增未存在的记录
		 * 
		 * @exitData : 已存在的子格数据
		 * @newData : 要导入的子表数据
		 * @primaryCol : 主键列
		 */
		matchDataForModify : function(exitData, newData, primaryCol,primaryKey) {
			//若字表数据为空，直接使用新数据
			if(exitData && !exitData.length) {
				return newData;
			}
			if(!primaryCol){
				utils.notify("修改模式未指定条件字段，请重新设置方案。");
				return;
			}
			primaryCol = primaryCol.split(",");//如果是多个条件逐渐特殊处理
			//给导入的数据建立主键索引
			var newDataMap = {};
			newData.each(function(v, i) {
				var pNames = [];
				for(var ix =0 , len = primaryCol.length; ix<len; ix++ ){
					pNames.push(v[primaryCol[ix]]);
				}
				newDataMap[pNames.join(",")] = v;				
			});
			//找出重复数据进行替换
			for(var i=0, j=exitData.length; i<j; i++) {
				var exitRecord = exitData[i];
	//			var key = exitRecord[primaryCol];
				var keys = [];//组合主键
				for(var idx =0 , len = primaryCol.length; idx<len; idx++ ){
					keys.push(exitRecord[primaryCol[idx]]);
				}
				keys = keys.join(",");
				if(typeof newDataMap[keys] !== 'undefined') {
					var dataMap = newDataMap[keys];
					delete dataMap [primaryKey];
					delete dataMap.modelState;
					delete dataMap.jcls;
					delete dataMap.classId;
					delete dataMap.typeId;
					for(dp in dataMap){
						if(exitRecord[dp] != dataMap[dp]){
							exitRecord[dp] = dataMap[dp];
							exitRecord.modelState = $.ecp.constants.ModelState.MODIFY;
						}
					}
					delete newDataMap[keys];
				}
			}
			//处理为匹配到的记录，已新增模式添加。
			for(var x in newDataMap) {
				exitData.push(newDataMap[x]);
			}
			return exitData;
		},
		
		/**
		 * 解析服务端返回的导入结果对象，返回有效数据和检验信息
		 * @ignore
		 * @param {Object} excelObj 导入的excel对象
		 * @return {Array} excelBook 对象数组
		 * @modify yinshanpeng@ygsoft.com
		 * @lastdate 2014.7.15
		 */
		_parseImportResult : function(excelObj) {
			if(utils.isEmpty(excelObj) === false) {
				var excelBook = new Array();
				for(var sheet in excelObj) {
					// showValidInfo : 是否显示校验信息 ，0：否 ，1：是 ; records : 映射数据信息
					var sheetVO = {
						records : {},
						showValidInfo : 0
					};
					sheetVO.records = excelObj[sheet].validData;
					//如果有非法信息，将 showValidInfo 设置为 1
					if(!utils.isEmpty(excelObj[sheet].invalidData)) {
						sheetVO.showValidInfo = 1;
					}
					excelBook.push(sheetVO);
				}
			}
			return excelBook;
		}
	};
	
	(function($) {
		var old = $.fn.ecpImport;
		$.fn.ecpImport = function(option){
			var me = this;
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var eus = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new EcpImport($(this), instanceOption);
					this.ecpImport = instance;
					eus.push(instance);
				});
				if(eus.length === 1){
					eus = eus[0];
				}
				return eus;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				if (EcpImport.prototype[option]) {
					return EcpImport.prototype[option].call(args);
				}
			} else if (option === true) {
				return me[0] && me[0].ecpImport;
			}
		};
		$.fn.ecpImport.Constructor = EcpImport;
		$.fn.ecpImport.noConflict = function() {
			$.fn.ecpImport = old;
			return this;
		};
	}(jQuery));
});